package com.leetcode.algorithm.y22.m06;

/**
 * 63. 不同路径 II
 * 
 * https://leetcode.cn/problems/unique-paths-ii/
 * 
 * @author jie.deng
 *
 */
class Question0063Solution02 {

	public int uniquePathsWithObstacles(int[][] obstacleGrid) {
		int m = obstacleGrid.length;
		int n = obstacleGrid[0].length;
		// DP状态定义
		// int[][] dp = new int[m][n];
		// 由dp[i][j]状态压缩得到dp[j]
		int[] dp = new int[n];

		// 初始化
		dp[0] = obstacleGrid[0][0] == 1 ? 0 : 1;
		for (int j = 1; j < n; j++) {
			dp[j] = obstacleGrid[0][j] == 1 ? 0 : dp[j - 1];
		}

		// 状态转移方程
		for (int i = 1; i < m; i++) {
			dp[0] = obstacleGrid[i][0] == 1 ? 0 : dp[0];
			for (int j = 1; j < n; j++) {
				dp[j] = obstacleGrid[i][j] == 1 ? 0 : dp[j] + dp[j - 1];
			}
		}

		return dp[n - 1];
	}

}